package com.fenghongzhang.lib_base.core

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

abstract class BaseViewModel<State : Any, Event : Any>(initialState: State) : ViewModel() {

    private val _state: MutableStateFlow<State> = MutableStateFlow(initialState)
    //20,更新这个值
    val state: StateFlow<State> = _state

    fun sendEvent(event: Event) {
        //3 协程处理事件
        viewModelScope.launch {
            handleEvent(event)
        }
    }

    // 4 谁实现,谁处理
    protected abstract suspend fun handleEvent(event: Event)

    //19, 状态更新
    protected fun updateState(newState: State) {
        _state.value = newState
    }
}

